package com.weilaiwd.admin.web;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.JsonKit;
import com.weilaiwd.admin.constant.Sql;
import com.weilaiwd.common.model.Channel;
import com.weilaiwd.common.web.BaseAction;

public class ChannelAction extends BaseAction {
	
	public void index() {
		List<Channel> channels = Channel.dao.find(Sql.Channel.findAll);
		JSONArray array = new JSONArray();
		for(Channel c:channels) {
			JSONObject json = new JSONObject();
			json.put("id", c.getInt("id"));
			json.put("pId", c.getInt("pid"));
			json.put("name", c.getStr("name"));
			array.add(json);
		}
		setAttr("treeJson", array.toString());
	}
	
	public void toAdd() {
		renderJsp("form.jsp");
	}
	
	public void load() {
		Channel channel = Channel.dao.findById(getPara());
		Channel parent = Channel.dao.findById(channel.getInt("pid"));
		channel.put("parent", parent);
		setAttr("channel", channel);
		renderJsp("form.jsp");
	}
	
	public void save() {
		Channel channel = getModel(Channel.class);
		Integer id = channel.getInt("id");
		if(id==null) 
			channel.save();
		else
			channel.update();
		JSONObject json = JSON.parseObject(JsonKit.toJson(channel));
		json.put("isAdd", id==null);
		success("保存成功！！", json);
	}
	
	public void del() {
		int id = getParaToInt();
		Channel.dao.deleteById(id);
		//删除父节点不存在的节点
		List<Channel> channels = Channel.dao.find(Sql.Channel.findNoParent);
		for(Channel channel:channels) {
			channel.delete();
		}
		success("删除成功！！", id);
	}
	
	public void tree() {
		List<Channel> channels = Channel.dao.find(Sql.Channel.findAll);
		JSONArray array = new JSONArray();
		for(Channel c:channels) {
			JSONObject json = new JSONObject();
			json.put("id", c.getInt("id"));
			json.put("pId", c.getInt("pid"));
			json.put("name", c.getStr("name"));
			array.add(json);
		}
		renderJson(array.toString());
	}

}
